<template>
  <div class="alloc-resource">
    <group-select
    v-for="rootMenu in resources" :key="rootMenu.id" :options="rootMenu"
    @handleChange="handleChange"></group-select>
    <div class="opt">
      <el-button type="primary" @click="onSubmit">确定</el-button>
      <el-button @click="$router.push({name:'role'})">取消</el-button>
    </div>
  </div>
</template>

<script>
import GroupSelect from './components/GroupSelect.vue';
// eslint-disable-next-line
import { GetRoleResources,UpdateRoleResources } from '@/services/role';

export default {
  name: 'AllocResource',
  props: ['id'],
  created() {
    this.loadResource();
  },
  data() {
    return {
      resources: [],
      SelectedRoles: {},
    };
  },
  components: {
    GroupSelect,
  },
  methods: {
    async loadResource() {
      const { data } = await GetRoleResources(this.id);
      if (data.code === '000000') {
        this.resources = data.data;
        this.resources.forEach((element) => {
          if (element.selected) {
            this.SelectedRoles[element.id] = element.resourceList
              .filter((sub) => sub.selected)
              .map((sub) => sub.id);
          }
        });
      }
    },
    handleChange(rootID, menus) {
      console.log(rootID);
      console.log(menus);
      this.SelectedRoles[rootID] = menus;
    },
    async onSubmit() {
      const resourceIdList = [];
      Object.keys(this.SelectedRoles).forEach((key) => {
        if (this.SelectedRoles[key].length > 0) {
          resourceIdList.push(key);
          resourceIdList.push(...this.SelectedRoles[key]);
        }
      });
      const { data } = await UpdateRoleResources({
        roleId: this.id, resourceIdList,
      });
      if (data.code === '000000') {
        this.$message.success('资源分配成功');
        this.$router.push({ name: 'role' });
      } else {
        this.$message.error('资源分配失败');
      }
      console.log(resourceIdList);
    },
  },
};
</script>
<style scoped>
.opt {
  display: flex;
  justify-content: center;
}
</style>
